/*
 * @Description:
 * @Author: william
 * @Date: 2025-02-05 09:08:10
 * @LastEditors: william
 * @LastEditTime: 2025-03-11 17:02:45
 */
import Cookies from 'js-cookie'
import { setCookieLang } from '@/utils/cookies'
import { getLanguage } from '@/lang/index'

export const useAppStore = defineStore('app', () => {
  const sidebar = ref({
    opened: Cookies.get('sidebarStatus')
      ? !!+Cookies.get('sidebarStatus')
      : true,
    withoutAnimation: false
  })
  const language = ref(getLanguage())
  const theme = ref('theme-white')
  const device = ref('desktop')
  const map = ref(
    localStorage.getItem('map') ? localStorage.getItem('map') : 'AMAP'
  )
  const msgTotal = ref(0)

  const toggleSideBar = () => {
    sidebar.value.opened = !sidebar.value.opened
    sidebar.value.withoutAnimation = false
    Cookies.set('sidebarStatus', sidebar.value.opened ? 1 : 0)
  }

  const setSideBar = status => {
    sidebar.value.opened = status
    Cookies.set('sidebarStatus', sidebar.value.opened ? 1 : 0)
  }

  const closeSideBar = withoutAnimation => {
    Cookies.set('sidebarStatus', 0)
    sidebar.value.opened = false
    sidebar.value.withoutAnimation = withoutAnimation
  }

  const toggleDevice = deviceValue => {
    device.value = deviceValue
  }

  const setLanguage = lang => {
    language.value = lang
    document.documentElement.setAttribute('language', lang)
    const DOM = document.getElementsByTagName('body')[0]
    lang === 'zh'
      ? DOM.classList.remove('english')
      : DOM.classList.add('english')
    localStorage.setItem('language', lang)
    setCookieLang(lang)
  }

  const setTheme = val => {
    theme.value = val
    const attrTheme = val === 'theme-blue' ? 'blue' : 'white'
    document.documentElement.setAttribute('theme', attrTheme)
    const bodyDom = document.getElementsByTagName('body')[0]
    val === 'theme-blue'
      ? bodyDom.classList.remove('white')
      : bodyDom.classList.add('white')
    localStorage.setItem('theme-color', val)
  }

  const setMap = mapValue => {
    map.value = mapValue
  }

  const setMsgTotal = total => {
    msgTotal.value = total
  }

  return {
    sidebar,
    language,
    theme,
    device,
    map,
    msgTotal,
    toggleSideBar,
    setSideBar,
    closeSideBar,
    toggleDevice,
    setLanguage,
    setTheme,
    setMap,
    setMsgTotal
  }
})

export function useOutsideAppStore() {
  return useAppStore(g_store)
}
